window.addEventListener("load", function () {
  var focus = document.querySelector(".focus");
  var leftbtn = document.querySelector(".focus_a");
  var rightbtn = document.querySelector(".focus_b");
  var focuswidth = focus.offsetWidth;
  focus.addEventListener("mouseenter", function () {
    leftbtn.style.display = "block";
    rightbtn.style.display = "block";
    clearInterval(timer);
    // 清空变量
    timer = null;
  });
  focus.addEventListener("mouseleave", function () {
    leftbtn.style.display = "none";
    rightbtn.style.display = "none";
    timer = setInterval(function () {
      rightbtn.click();
    }, 2000);
  });
  var ul = focus.querySelector("ul");

  var ol = focus.querySelector("ol");
  for (var i = 0; i < ul.children.length; i++) {
    var li = document.createElement("li");
    //给每个li 设置索引号
    li.setAttribute("index", i);
    ol.appendChild(li);
    li.addEventListener("click", function () {
      for (var i = 0; i < ol.children.length; i++) {
        ol.children[i].className = "";
      }
      this.className = "current";
      //this 指的是当前点击的li元素
      var index = this.getAttribute("index");
      // num 控制的是点击按钮的索引号
      num = index;
      // circle 控制的是小圆圈的索引号
      circle = index;
      animate(ul, -index * focuswidth);
    });
  }
  ol.children[0].className = "current";
  var num = 0;
  var li2 = ul.children[0].cloneNode(true);
  ul.appendChild(li2);
  var circle = 0;
  var flag = true;
  rightbtn.addEventListener("click", function () {
    if (flag) {
      flag = false;
      if (num == ul.children.length - 1) {
        ul.style.left = 0;
        num = 0;
      }
      num++;
      animate(ul, -num * focuswidth, function () {
        flag = true;
      });
      circle++;
      if (circle == ol.children.length) {
        circle = 0;
      }
      for (var i = 0; i < ol.children.length; i++) {
        ol.children[i].className = "";
      }
      ol.children[circle].className = "current";
    }
  });
  leftbtn.addEventListener("click", function () {
    if (flag) {
      flag = false;
      if (num == 0) {
        num = ul.children.length - 1;
        ul.style.left = -num * focuswidth + "px";
      }
      num--;
      animate(ul, -num * focuswidth, function () {
        flag = true;
      });
      circle--;
      if (circle < 0) {
        circle = ol.children.length - 1;
      }
      for (var i = 0; i < ol.children.length; i++) {
        ol.children[i].className = "";
      }
      ol.children[circle].className = "current";
    }
  });
  // 自动播放
  var timer = setInterval(function () {
    rightbtn.click();
  }, 2000);
});
